package service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import nuonuo.com.aidl.Book;
import nuonuo.com.aidl.IBookManager;
import nuonuo.com.aidl.IOnNewBookArrivedListener;

public class AidlService extends Service {

    private ArrayList<Book> mList = new ArrayList<>();
    private RemoteCallbackList<IOnNewBookArrivedListener> mListeners = new RemoteCallbackList<>();

    private Binder mBinder = new IBookManager.Stub() {
        @Override
        public List<Book> getBookList() throws RemoteException {
            return mList;
        }

        @Override
        public synchronized void addBook(Book book) throws RemoteException {
            mList.add(book);
            mPool.submit(new NotifyThread(book));
        }

        @Override
        public void registOnBookChangedListener(IOnNewBookArrivedListener listener) throws RemoteException {
            mListeners.register(listener);
        }

        @Override
        public void unregistOnBookChangedListener(IOnNewBookArrivedListener listener) throws RemoteException {
            mListeners.unregister(listener);
        }
    };
    private final ExecutorService mPool;

    public AidlService() {
        mList.add(new Book("01","第一行代码"));
        mList.add(new Book("02","第二行代码"));
        mPool = Executors.newFixedThreadPool(1);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class NotifyThread extends Thread{

        private Book mBook;

        public NotifyThread(Book book){
            mBook = book;
        }

        @Override
        public void run() {
            int num = mListeners.beginBroadcast();
            for (int i = 0; i < num; i++) {
                try {
                    mListeners.getBroadcastItem(i).onBookChanged(mBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            mListeners.finishBroadcast();
        }
    }
}
